<template>
    <div class="content">
        <el-upload
            action=""
            class="upload-demo"
            accept=".xlsx, .xls"
            :on-exceed="exceedFile"
            :on-error="handleError"
            :on-success="handleSuccess"
            :http-request="uploadExcel"
            :before-upload="beforeUPload"
            :show-file-list="false"
            :limit="1"
        >
            <el-button type="success" icon="Upload">{{ importTitle }}</el-button>
        </el-upload>
        <el-button
            type="primary"
            icon="download"
            text
            @click="dewnloadTemp"
            style="margin-left: 5px"
        >
            {{ tempTitle }}
        </el-button>
    </div>
</template>

<script setup lang="ts">
import { MessageCustom } from "@/utils/message"
import { importExcel } from "@/api/common/common"

const props = defineProps({
    importTitle: {
        type: String,
        default: "导入数据",
    },
    tempTitle: {
        type: String,
        default: "下载模板",
    },
    url: {
        type: String,
        default: "",
        require: true,
    },
})

const emit = defineEmits(["uploadSuccess", "downloadTempClick"])

function dewnloadTemp() {
    emit("downloadTempClick")
}

// 文件上传之前判断
const beforeUPload = (file: any) => {
    const isExcel =
        file.type === "application/vnd.ms-excel" ||
        file.type === "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
    const isLt2M = file.size / 1024 / 1024 < 20
    if (!isExcel) MessageCustom("error", "上传文件只能是 xls / xlsx 格式！")
    if (!isLt2M) MessageCustom("error", "上传文件大小不能超过 20MB!")
    return isExcel && isLt2M
}
// 文件数超出提示
const exceedFile = () => {
    MessageCustom("error", "最多只能上传一个文件！")
}
// 上传错误提示
const handleError = () => {
    MessageCustom("error", "导入数据失败，请您重新上传！")
}

//上传成功提示
const handleSuccess = () => {
    emit("uploadSuccess")
    MessageCustom("success", "导入数据成功！")
}

//文件上传
const uploadExcel = async (param: any) => {
    const res = await importExcel(props.url, param.file)
    if (res.code !== 0) return param.onError()
}
</script>

<style lang="less" scoped>
.content {
    display: flex;
}
</style>
